import { Ollama } from "ollama/browser";
import { useChatStore } from '@/chat/store'

const ollama = new Ollama({ host: window.location.origin })

export function chat(content: string, contentList: any = []) {
  const chatStore = useChatStore()
  const messages: any = []
  if (chatStore.currentChat.prompt) {
    messages.push({ role: "system", content: chatStore.currentChat.prompt })
  }
  if (contentList.length) {
    // 会话历史
    let history: any = [...contentList].slice(2)
    history.reverse()
    const len = history.length
    const size = len > 20 ? len - 20 : 0
    history.slice(size).map((item: any) => {
      messages.push({
        role: item.role,
        content: item.content
      })
    })
  }
  messages.push({ role: "user", content: content })
  return ollama.chat({
    model: chatStore.currentChat.model,
    options: { temperature: chatStore.currentChat.temperature || 0.5 },
    messages: messages,
    stream: true,
  });
}

export function listModels() {
  return new Promise((resolve) => {
    const models = sessionStorage.getItem('models')
    if (models) {
      resolve(JSON.parse(models))
    } else {
      ollama.list().then((res) => {
        sessionStorage.setItem('models', JSON.stringify(res))
        resolve(res)
      })
    }
  })
}

export function abort() {
  ollama.abort();
}
